﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using BLL;
using System.Text;
using Models;
using Tools;
using webui.ViewModel;
using NLog;
using SqlSugar;
using webui.Models;
using BLL.TableBLL;
using Models.TableModel;

namespace webui.Controllers
{
    public class HomeController : Controller
    {
        //地址
        string apiurl = System.Configuration.ConfigurationSettings.AppSettings["httpip"];

        public NewsContentBLL inewsbll = new NewsContentBLL();
      
        public NewsTypeBLL inewstype = new NewsTypeBLL();
        
        public NewsCommentBLL icoment = new NewsCommentBLL();

    
        /// <summary>
        /// 显示首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
           // setNavigation(); // 1.0设置首页标题
           // //Logger.Default.Debug("调试发生了什么"); 
           ////2.0设置Flash 幻灯片。
           ////1.读取数据 
           //PageModel page = new PageModel()
           // {
           //     PageIndex = 1,
           //     PageSize = 4,
           //     PageCount = 0
           // };
           // var newsimg = inewsbll.GetPageList(p => p.newsImage != "" && p.newsImage != null && p.isDel == false, page, p => p.id, OrderByType.Desc).ToList();



           // StringBuilder files = new StringBuilder();
           // StringBuilder links = new StringBuilder();
           // StringBuilder texts = new StringBuilder();
           // foreach (var item in newsimg)
           // {
           //     files.Append("../../upimg/" + item.newsImage + "|");
           //     links.Append("../../home/newsdetail?id=" + item.id + "|");
           //     texts.Append(substr(item.title, 19) + "|");

           // }
           // ViewBag.files = files.ToString().Substring(0, files.Length - 1);
           // ViewBag.links = links.ToString().Substring(0, links.Length - 1);
           // ViewBag.texts = texts.ToString().Substring(0, texts.Length - 1);

           // //3.0 设置最新的新闻 -幻灯片旁边。
           // page.PageSize = 7;
           // var news7 = inewsbll.GetPageList(p => p.isDel == false, page, p => p.id, OrderByType.Desc).ToList();

           // ViewBag.toptitle = "<a href='../../home/newsdetail?id=" + news7[0].id + "'>" + substr(news7[0].title, 40) + "</a>";
           // news7.RemoveAt(0);
           // for (int i = 0; i < news7.Count; i++)
           // {
           //     news7[i].title = substr(news7[i].title, 22);  //过滤标题长度
           // }
           // ViewBag.newtitle = news7;

           // // 4.设置阅读排行的新闻。
           // page.PageSize = 10;
           // var newsHot = inewsbll.GetPageList(p => p.isDel == false, page, p => p.hot, OrderByType.Desc).ToList();
             
           // for (int i = 0; i < newsHot.Count; i++)
           // {
           //     newsHot[i].title = substr(newsHot[i].title, 13);  //过滤标题长度
           // }           
           // ViewBag.newsHot = newsHot;

            return View();
        }



        [HttpGet]
        /// <summary>
        /// 查询列表 视图
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList( string str )
        {

            string ajaxurl = apiurl + "api/Query/GetBooklist?pname=" + str;

            ResponViewBaicjourna obdata = Tools.RestHelper.GeteByT<ResponViewBaicjourna>(ajaxurl);
           
            return OperateContext.Current.RedirectAjax(obdata.Status, obdata.Msg, obdata.Data, "");
        }



        /// <summary>
        /// 详细 视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Detail(string gch)
        {
           // string ajaxurl = apiurl + "api/Query/GetRecently?gch=" + gch;
            //ResponViewBaicjourna obdata = Tools.RestHelper.GeteByT<ResponViewBaicjourna>(ajaxurl);
            //return OperateContext.Current.RedirectAjax(obdata.Status, obdata.Msg, obdata.Data, "");
            return View();
        }


        /// <summary>
        /// 查询列表 
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDetail(string gch)
        {
            string ajaxurl = apiurl + "api/Query/GetRecently?gch="+ gch;
            ResponViewBaicjourna obdata = Tools.RestHelper.GeteByT<ResponViewBaicjourna>(ajaxurl);
            return OperateContext.Current.RedirectAjax(obdata.Status, obdata.Msg, obdata.Data, "");

        }


        /// <summary>
        /// 获取下载 
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDown(int years,string vol, string gch, string num, string panme)
        {
           bool   isLogin = OperateContext.Current.IsLogin();
            if (isLogin)
            {

                //判断下载次数,  加入下载列表
                BLL.UserInfoBLL ubll = new BLL.UserInfoBLL();
                var umodle = ubll.GetSingle(s => s.loginname == OperateContext.Current.Usr.loginname);
                OperateContext.Current.Usr = umodle;
                if (umodle.downNum<1)
                {
                    return OperateContext.Current.RedirectAjax(2, "下载次数不够，请到后台充值", "", "");
                }



                DownLog model = new DownLog();
                model.gch = gch;
                model.years = years;
                model.vol = vol;
                model.num = num;
                model.pname = panme;
                model.downtiem = DateTime.Now;
                model.userid = OperateContext.Current.Usr.id;

               

                DownLogBLL dbll = new DownLogBLL();
                bool iskouFen = true;
                //是否下载过
                if (dbll.IsAny(s => s.gch == gch && s.num == num && s.years == years))
                {
                    DownLog dr  = dbll.GetList(s => s.gch == gch && s.num == num).FirstOrDefault();
                    model.downState = dr.downState;// 下载过的修状态
                    if (dr.userid==umodle.id)
                    {
                        //不扣分
                        iskouFen = false;
                        return OperateContext.Current.RedirectAjax(1, "云加载成功，请在后台中下载。", "", "");
                    }
                }
                else
                { 
                    model.downState = 0;
                    // 启动服务下载
                }
                if (iskouFen)
                {
                    umodle.downNum = umodle.downNum - 1;
                    ubll.Update(umodle);
                    //扣分
                }
                dbll.Insert(model);

                return OperateContext.Current.RedirectAjax(1, "云加载成功....请在后台下载管理中查看。", "", "");


            }
            else
            {
                return OperateContext.Current.RedirectAjax(-1, "还没登录", "", "");
            }

            return OperateContext.Current.RedirectAjax(0, "错误", "", "");

        }



        #region 过时的



        /// <summary>
        /// 首页生成各大模块新闻列表
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        public string GetTypeNews(int tid)
        {

            PageModel page = new PageModel()
            {
                PageIndex = 1,
                PageSize = 10,
                PageCount = 0
            };
            var list = inewsbll.GetPageList(p => p.newsTypeid == tid && p.isDel == false, page, p => p.id, OrderByType.Desc).ToList();



            StringBuilder reult = new StringBuilder();
            foreach (var item in list)
            {
                reult.Append("<li><a href=\"../../home/newsdetail?id=" + item.id + " \">" + substr(item.title, 20) + "</a></li>");
            }

            return reult.ToString();
        }

        /// <summary>
        /// 新闻类型  视图页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ntype()
        {
            int typeid = 0;
            int.TryParse(Request["typeid"] ?? "0", out typeid);
            var aa = inewstype.GetList(p => p.id == typeid);

            if (typeid == 0 || aa.Count == 0)
            {
                return new RedirectResult("index");
            }
            setNavigation(); //设置显示导航

            NewsType modeltype = inewstype.GetSingle(p => p.id == typeid);
            ViewBag.typename = modeltype.typeName; //显示新闻类型。



            // 3.设置阅读排行的新闻。
            PageModel page = new PageModel()
            {
                PageIndex = 1,
                PageSize = 10,
                PageCount = 0
            };
            var newsHot = inewsbll.GetPageList(p => p.isDel == false && p.newsTypeid == typeid, page, p => p.id, OrderByType.Desc).ToList();
            for (int i = 0; i < newsHot.Count; i++)
            {
                newsHot[i].title = substr(newsHot[i].title, 13);  //过滤标题长度
            }
            ViewBag.newsHot = newsHot;
            return View();
        }

        /// <summary>
        /// 分页获取新闻列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPageType()
        {
            int pageSize = int.Parse(Request["pageSize"] ?? "10");
            int pageIndex = int.Parse(Request["pageIndex"] ?? "1");
            int typeid = int.Parse(Request["typeid"] ?? "0");
            int total = 0;

            if (typeid == 0)
            {
                Response.Redirect("index");
            }
            // 2.获取本类型分页新闻列表。 


            PageModel page = new PageModel()
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                PageCount = 0
            };
            var newslist = inewsbll.GetPageList(p => p.isDel == false && p.newsTypeid == typeid, page, p => p.id, OrderByType.Desc).ToList();


            for (int i = 0; i < newslist.Count; i++)
            {
                newslist[i].title = substr(newslist[i].title, 40);  //过滤标题长度
                newslist[i].content = "";  //减少传输量
            }
            //3.获取分页条
            var mainPager = OperateContext.ShowPageNavigate(pageSize, pageIndex, page.PageCount);
            ViewBag.MainPager = MvcHtmlString.Create(mainPager);

            return OperateContext.Current.RedirectAjax("ok", "", new { NewsList = newslist, NavHtml = mainPager }, "");

        }

        /// <summary>
        /// 显示 新闻详情页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Newsdetail()
        {

            //  Logger.Default.Info("记录日常业务信息");

            int id = 0;
            int.TryParse(Request["id"] ?? "0", out id);
            var aa = inewsbll.GetList(p => p.id == id);

            if (id == 0 || aa.Count == 0)
            {
                //查询新闻是否存在
                return new RedirectResult("index");
            }

            //新闻阅读数量+1
            var model = inewsbll.GetSingle(p => p.id == id);
            model.hot = model.hot + 1;
            inewsbll.Update(model);
            setNavigation(); //1设置显示导航

            //2.查询新闻详情

            ViewBag.typename = model.newsTypeid;
            model.content = Server.HtmlDecode(model.content);
            ViewBag.news = model;

            // 3.设置阅读排行的新闻。


            PageModel page = new PageModel()
            {
                PageIndex = 1,
                PageSize = 10,
                PageCount = 0
            };
            var newsHot = inewsbll.GetPageList(p => p.isDel == false, page, p => p.hot, OrderByType.Desc).ToList();
            for (int i = 0; i < newsHot.Count; i++)
            {
                newsHot[i].title = substr(newsHot[i].title, 13);  //过滤标题长度
            }
            ViewBag.newsHot = newsHot;
            int bb = (int)model.hot + 1;
            return View();
        }


        //实现前台的验证码
        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(4);
            Session["Code"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }



        [HttpPost]
        [ValidateInput(false)]

        //添加评论
        public ActionResult Addcomment(NewsComment comModl)
        {
            string code = Request["verfiy"] ?? "";
            if (Session["Code"].ToString() == code)
            {
                if (!(string.IsNullOrEmpty(comModl.nickName) || comModl.nickName.Length > 10 || string.IsNullOrEmpty(comModl.Comment) || comModl.Comment.Length > 200 || comModl.newsid == 0))
                {
                    comModl.addtime = DateTime.Now;
                    comModl.userIp = Request.UserHostAddress;
                    comModl.Comment = Server.HtmlEncode(comModl.Comment); //将HTML编码。
                    try
                    {
                        //  var aa = comModl.MapTo<NewsComment, V_NewsComment>();
                        icoment.Insert(comModl);
                        return OperateContext.Current.RedirectAjax("ok", "添加成功", null, "newsview");
                    }
                    catch (Exception ce)
                    {
                        return OperateContext.Current.RedirectAjax("err", "添加失败" + ce.Message, null, "");
                    }

                }
                else
                {
                    return OperateContext.Current.RedirectAjax("err", "信息填写错误", null, "");
                }
            }
            else
            {
                return OperateContext.Current.RedirectAjax("err", "验证码错误", null, "");
            }
        }


        //分页显示评论
        public ActionResult GetPageComment()
        {
            int pageSize = int.Parse(Request["pageSize"] ?? "10");
            int pageIndex = int.Parse(Request["pageIndex"] ?? "1");
            int newsid = int.Parse(Request["id"] ?? "1");
            int total = 0;

            if (newsid == 0)
            {
                Response.Redirect("index");
            }
            // 2.获取本类型分页新闻列表。 


            PageModel page = new PageModel()
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                PageCount = 0
            };
            var newslist = icoment.GetPageList(p => p.newsid == newsid, page, p => p.id, OrderByType.Desc).ToList();
            //3.获取分页条
            var mainPager = OperateContext.ShowPageNavigate(pageSize, pageIndex, total);
            ViewBag.MainPager = MvcHtmlString.Create(mainPager);
            return OperateContext.Current.RedirectAjax("ok", "", new { NewsList = newslist, NavHtml = mainPager }, "");

        }



        /// <summary>
        /// 设置显示导航
        /// </summary>
        void setNavigation()
        {
            // 1.0设置首页标题
            var newstype = inewstype.GetList(p => p.isDel == false).OrderBy(u => u.id).ToList();
            ViewBag.newstype = newstype;
        }


        /// <summary>
        /// 截取字符串长度,返回加...
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="num">截取位数</param>
        /// <returns></returns>
        string substr(string str, int num)
        {
            if (str.Length > num)
            {
                return str.Substring(0, num) + "...";

            }
            else
            {
                return str;
            }
        }

        #endregion


    }
}